import { defineComponent, ref } from "vue";
import { useI18n } from "vue-i18n";

export default defineComponent({
  props: {
    courses: {
      type: Array,
      default: () => [],
    },
    everyPageCount: {
      type: Number,
      default: 9,
    },
    currentPage: {
      type: Number,
      default: 1,
    },
  },
  emits: ["handlePage"],
  setup(props, { emit }) {
    const count = props.courses.length || 9;
    const pages = Math.ceil(count / props.everyPageCount);
    const current = ref(props.currentPage);

    const handlePage = (isappoint: boolean, page = 1) => {
      isappoint || (current.value += page);
      emit("handlePage", {
        isappoint,
        page,
      });
    };

    const { t } = useI18n();
    return () => {
      if (pages > 1) {
        return (
          <div class="flex select-none">
            <div
              class={[
                "flex items-center px-4 py-2 mx-1 text-gray-500 bg-white rounded-md shadow-md cursor-pointer",
                current.value <= 1 && "cursor-not-allowed",
              ]}
              onClick={() => {
                current.value > 1 && handlePage(false, -1);
              }}
            >
              {t("page.previous")}
            </div>
            {Array(pages)
              .fill(0)
              .map((item, index) => {
                return (
                  <div
                    class={[
                      "flex items-center px-4 py-2 mx-1 transition-colors duration-200 transform rounded-md shadow-md hover:bg-mainColor hover:text-white cursor-pointer",
                      index + 1 === current.value
                        ? "bg-mainColor text-white"
                        : "text-gray-700 bg-white",
                    ]}
                    onClick={() => {
                      current.value = index + 1;
                      handlePage(true, current.value);
                    }}
                  >
                    {index + 1}
                  </div>
                );
              })}
            <div
              class={[
                "flex items-center px-4 py-2 mx-1 text-gray-700 transition-colors duration-200 transform bg-white rounded-md shadow-md cursor-pointer",
                current.value >= pages && "cursor-not-allowed",
              ]}
              onClick={() => {
                current.value < pages && handlePage(false, 1);
              }}
            >
              {t("page.next")}
            </div>
          </div>
        );
      }
    };
  },
});
